package com.euc.springbootframework.controller.base;

import com.euc.springbootframework.service.base.RestBaseService;
import org.springframework.beans.factory.annotation.Autowired;

import javax.validation.ConstraintViolation;
import javax.validation.Validator;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;


public abstract class RESTBaseController<T> {


    public abstract RestBaseService<T> getRestService();
    protected Logger logger=LoggerFactory.getLogger(this.getClass().getName());

    @Autowired
    private Validator validator;

    @RequestMapping(value = "/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public ResponseEntity<?> get(@PathVariable("id") String id) {
        T task = getRestService().findOne(id);
        if (task == null) {
            return new ResponseEntity<Object>(HttpStatus.NOT_FOUND);
        }
        return new ResponseEntity<Object>(task, HttpStatus.OK);
    }

    @RequestMapping(value = "/", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public List<?> getAll(){
        List<?> result = getRestService().findAll();
        return result;
    }

    @SuppressWarnings("unchecked")
    @RequestMapping(method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public ResponseEntity<?> create(@RequestBody T task) {
        Set<ConstraintViolation<T>> failures = validator.validate(task);
        T result = getRestService().save(task);
        return new ResponseEntity<T>(result, HttpStatus.CREATED);
    }


}
